<?php
/**
 * NOTICE OF LICENSE
 *
 * This source file is subject to the  Academic Free License (AFL 3.0)
 * that is available through the world-wide-web at this URL:
 * http://opensource.org/licenses/afl-3.0.php
 * If you did not receive a copy of the license and are unable to
 * obtain it through the world-wide-web, please send an email
 * to support@zprofess.com so we can send you a copy immediately.
 *
 * @category   	Prestashop module
 * @package		Help Desk
 * @version 	1.0
 * @author 		Kurosaki <kurosaki@zprofess.com>
 * @copyright   Copyright (c) 2012 ZPROFESS. (http://zprofess.com)
 * @license    	http://opensource.org/licenses/afl-3.0.php  Academic Free License (AFL 3.0)
 */

include_once(dirname(__FILE__).'/../../classes/AdminTab.php');
include_once(dirname(__FILE__).'/classes/ZdepartmentObject.php');
include_once(dirname(__FILE__).'/classes/ZemployeesGrid.php');

require_once(dirname(__FILE__).'/lib/zprofess/ZhelpdeskadminTab.php');

class Zadmindepartmentcontent extends ZhelpdeskadminTab
{
	/** @var object new list employee */
	 private $staffGrid = null;
	 /** table name employee	  */
	 private $childTable = 'employee';
	/**
     * Sole constructor
    */ 
	public function  __construct()
	{
            $this->edit = true;
            $this->delete = true;
            $this->lang = true;

            $this->table = 'zhelpdesk_department';
            $this->className = 'ZDepartmentObject';
            
            $this->_select = 'CONCAT_WS(" ", ze.`firstname`, ze.`lastname`) as namemod';
 		// join Moderator(employee)
            $this->_join = 'LEFT JOIN `' . _DB_PREFIX_ . 'employee` as ze ON (ze.`id_employee` = a.`id_moderator`)';
                
            $this->fieldsDisplay = array(						
                    'id_zhelpdesk_department' => array('title' => $this->l('ID'), 'align' => 'center', 'width' => 25 ),
                    'name' => array('title' => $this->l('Name'),'width' => 200 ,'align' => 'center', 'maxlength' => 150),
                    'namemod' => array('title' => $this->l('Moderator'),'width' => 250 ,'align' => 'center', 'maxlength' => 250),
//			'description' => array('title' => $this->l('Description'),'width' => 300 ,'align' => 'center', 'maxlength' => 200, 'type' => 'textLang'),		
                    'require_login' => array('title' => $this->l('Require login'), 'align' => 'center', 'active' => 'require_login', 'type' => 'bool'),
//			'date_upd' => array('title' => $this->l('Date Update'), 'type'=>'datetime' ,'align' => 'right', 'width' => 80),
                    'active' => array('title' => $this->l('Active'), 'align' => 'center', 'active' => 'status', 'type' => 'bool'),		
            );
        
            $this->staffGrid = new ZEmployeesGrid();
        
            parent::__construct();
	}
	
	/**
	 * @see AdminTabs->postProcess();
	 * 
	 * Manage page processing
	 *
	 * @global string $currentIndex Current URL in order to keep current Tab
	 */
	public function postProcess()
	{
		global $currentIndex, $cookie;	
		$object = new $this->className();
		$token = Tools::getValue('token') ? Tools::getValue('token') : $this->token;
		
		/* Cancel all filters for this tab (Reset) */
		if (Tools::isSubmit('submitReset'.$this->childTable)) {
			
			if(isset($_POST['id_'.$this->table]))
				$id_table = $_POST['id_'.$this->table];
			
			//save cokie continue
			foreach ($_POST AS $key => $value){
				if (key_exists($key, $object) AND $key != 'id_'.$this->table){
					$cookie->{$key} = $value;
				}
			}
			$this->staffGrid->postProcess();
			
			if (isset($id_table)) {
				Tools::redirectAdmin($currentIndex.'&id_'.$this->table.'='.(int)$id_table.'&update'.$this->table.'&id_tab=1&copy&token='.$token);
			} else {
				Tools::redirectAdmin($currentIndex.'&add'.$this->table.'&id_tab=1&copy&token='.$token);
			}
		}
		
		/* Manage list filtering */
		elseif (Tools::isSubmit('submitFilter'.$this->childTable) OR $cookie->{'submitFilter'.$this->childTable} !== false){
			if(isset($_POST['id_'.$this->table]))
				$id_table = $_POST['id_'.$this->table];
				
			if(isset($_POST['pagination'])) {
				$cookie->{$this->childTable.'_pagination'} = Tools::getValue('pagination');
			}
			//save cokie continue
			foreach ($_POST AS $key => $value){
				if (key_exists($key, $object) AND $key != 'id_'.$this->table){
					$cookie->{$key} = $value;
				}
			}
			$this->staffGrid->postProcess();
			
			if (Tools::isSubmit('submitFilter' . $this->childTable) && isset($_POST['submitFilter'])) {
				if (isset($id_table)) {
					Tools::redirectAdmin($currentIndex.'&id_'.$this->table.'='.(int)$id_table.'&update'.$this->table.'&id_tab=1&copy&token='.$token);
				} else {
					Tools::redirectAdmin($currentIndex.'&add'.$this->table.'&id_tab=1&copy&token='.$token);
				}
			}
		}
		
		/* Change object require_login (active, inactive) */
		if ((isset($_GET['require_login'.$this->table]) OR isset($_GET['require_login'])) AND Tools::getValue($this->identifier))
		{
			if ($this->tabAccess['edit'] === '1')
			{
				if (Validate::isLoadedObject($object = $this->loadObject()))
				{
					if ($object->toggleRequireLogin())
						Tools::redirectAdmin($currentIndex.'&conf=4'.((($id_category = (int)(Tools::getValue('id_category'))) AND Tools::getValue('id_product')) ? '&id_category='.$id_category : '').'&token='.$token);
					else
						$this->_errors[] = Tools::displayError('An error occurred while updating status.');
				}
				else
					$this->_errors[] = Tools::displayError('An error occurred while updating status for object.').' <b>'.$this->table.'</b> '.Tools::displayError('(cannot load object)');
			}
			else
				$this->_errors[] = Tools::displayError('You do not have permission to edit here.');
		}
		
		// creat object then delete cookie form post
		if(Tools::isSubmit('submitAdd'.$this->table) AND Tools::getValue('submitAdd'.$this->table))
		{
			if (!Tools::getValue('id_moderator'))
				$this->_errors[] = Tools::displayError('Please select moderator department .');
			/* Delete cookie copy form post */
	 		foreach ($_POST AS $key => $value){
				if (key_exists($key, $object) AND $key != 'id_'.$this->table){
					if (isset($cookie->{$key}))
						unset($cookie->{$key});
				}
			}
		}
		
		parent::postProcess();
	}
	/**
	 * 
	 * @see AdminTabs->displayForm()
	 * @param $isMainTab
	 */
	public function displayForm($isMainTab = true)
	{		
	    global $currentIndex, $cookie;
		parent::displayForm();
		$object = new $this->className();
		if (!($obj = $this->loadObject(true)))
            return;
		// copy form post
		if(isset($_GET['copy'])){
			foreach ($object AS $key=>$value){
				if(isset($cookie->{$key})){
					$obj->{$key} = $cookie->{$key};
				}
			}
		}
        // load js editor  
        $this->_prepareJs();
        echo '
            <script type="text/javascript">
                var pos_select = '.(($tab = Tools::getValue('id_tab')) ? $tab : '0').';
            </script>
            <script src="../js/tabpane.js" type="text/javascript"></script>
            <link type="text/css" rel="stylesheet" href="../css/tabpane.css" />
               ';
        echo '
            <form action="' . $currentIndex . '&submitAdd' . $this->table . '=1&token=' . $this->token . '" method="post" autocomplete=off>
                ' . ($obj->id ? '<input type="hidden" name="id_' . $this->table . '" value="' . $obj->id . '" />' : '') . '
                <input type="hidden" name="tabs" id="tabs" value="0" />
                <div class="tab-pane" id="tabPane1">';
        $this->displayInformationTab($obj);
        $this->displayStaffTab($obj);
        echo '
	                <script type="text/javascript">
	                    function loadTab(id) {};
	                </script>
                </div> 
                <div class="clear">&nbsp;</div>         
            </form>
           ';
        
	}
	
	/**
     *  display tab Information
     *
     * @global  $cookie
     * @param <type> $obj
     */
    public function displayInformationTab($obj){
        global $cookie;
        $langtags = 'name¤description';
        echo '
            <div class="tab-page" id="step1">
           		<h4 class="tab">1. '.$this->l('Information.').'</h4>';
        echo $this->addElement('text', array ('label'=>'Name','name'=>'name', 'note'=>'','more'=>'size="50"', 'langtags'=>$langtags), true);
        echo $this->addElement('area', array ('label'=>'Description','name'=>'description', 'note'=>'', 'langtags'=>$langtags, 'class'=>'rte'), true);
        echo $this->addElement('yesno', array ('label'=>'Require login','name'=>'require_login'));
        echo $this->addElement('yesno', array ('label'=>'Active','name'=>'active'));
        
        // autocomplete select employee to Moderator
        echo '
        		<label>'.$this->l('Moderator').' </label><sup> *</sup>
				<div class="margin-form">';
		// get mode by id	
		$employeeInContent = ZDepartmentObject::_getModeById($this->getFieldValue($obj, 'id_moderator'));
		echo '
				<div id="divZTypeEmployee">';
//		foreach ($employeeInContent as $employee)
			echo htmlentities($employeeInContent['firstname'].' '.$employeeInContent['lastname'], ENT_COMPAT, 'UTF-8').' <span onclick="delZTypeEmployee('.$employeeInContent['id_employee'].');" style="cursor: pointer;"><img src="../img/admin/delete.gif" class="middle" alt="" /></span><br />';
		echo '
				</div>
				<input type="hidden" name="id_moderator" id="inputZTypeEmployee" value="';
//		foreach ($employeeInContent as $employee)
			echo (int)$employeeInContent['id_employee'];
		echo '" />
				<input type="hidden" name="nameZTypeEmployee" id="nameZTypeEmployee" value="';
//		foreach ($employeeInContent as $employee)
			echo htmlentities($employeeInContent['name'], ENT_COMPAT, 'UTF-8');
	
		echo '" />
				<script type="text/javascript">
					var formProduct;
					var accessories = new Array();
				</script>

				<link rel="stylesheet" type="text/css" href="'.__PS_BASE_URI__.'css/jquery.autocomplete.css" />
				<script type="text/javascript" src="'.__PS_BASE_URI__.'js/jquery/jquery.autocomplete.js"></script>
				<div id="ajax_choose_product" style="padding:6px; padding-top:2px; width:600px;">
					<p class="clear">'.$this->l('Begin typing the first letters of the lastname or firstname employee, then select the employee from the drop-down list:').'</p>
					<input type="text" value="" id="employee_autocomplete_input" size="50" />
				</div>
				<div class="clear">&nbsp;</div>';
?>
				<script type="text/javascript">
					urlToCall = null;
					/* function autocomplete */
					$(function() {
						$('#employee_autocomplete_input')
							.autocomplete( 
								'../modules/zhelpdesk/ajax/ajax_employee_list.php', {
								//'ajax_employee_list.php', {
								minChars: 1,
								autoFill: true,
								max:20,
								matchContains: true,
								mustMatch:true,
								scroll:false,
								cacheLength:0,
								formatItem: function(item) {
									return item[1]+' - '+item[0];
								}
							}).result(addZTypeEmployee);
						$('#employee_autocomplete_input').setOptions({
							extraParams: {excludeIds : getZemployeeIds()}
						});
					});
					
					function getZemployeeIds()
					{
						var ids = '. $obj->id.'+',';
						ids += $('#inputZTypeEmployee').val().replace(/\-/g,',').replace(/\,$/,'');
						ids = ids.replace(/\,$/,'');
			
						return ids;
			
					}					
					function addZTypeEmployee(event, data, formatted)
					{
						if (data == null)
							return false;
						var productId = data[1];
						var productName = data[0];
					
						var $divZTypeEmployee = $('#divZTypeEmployee');
						var $inputZTypeEmployee = $('#inputZTypeEmployee');
						var $nameZTypeEmployee = $('#nameZTypeEmployee');
					
						/* delete product from select + add product line to the div, input_name, input_ids elements */
						$divZTypeEmployee.html(productName + ' <span onclick="delZTypeEmployee(' + productId + ');" style="cursor: pointer;"><img src="../img/admin/delete.gif" /></span><br />');
						$nameZTypeEmployee.val(productName);
						$inputZTypeEmployee.val(productId);
						$('#employee_autocomplete_input').val('');
						$('#employee_autocomplete_input').setOptions({
							extraParams: {excludeIds : getZemployeeIds()}
						});
					}
					
					
					function delZTypeEmployee(id)
					{
						var div = getE('divZTypeEmployee');
						var input = getE('inputZTypeEmployee');
						var name = getE('nameZTypeEmployee');
					
						// Cut hidden fields in array
						var inputCut = input.value.split('-');
						var nameCut = name.value.split('¤');
					
						if (inputCut.length != nameCut.length)
							return alert('Bad size');
					
						// Reset all hidden fields
						input.value = '';
						name.value = '';
						div.innerHTML = '';
						for (i in inputCut)
						{
							// If empty, error, next
							if (!inputCut[i] || !nameCut[i])
								continue ;
					
							// Add to hidden fields no selected products OR add to select field selected product
							if (inputCut[i] != id)
							{
								input.value += inputCut[i] + '-';
								name.value += nameCut[i] + '¤';
								div.innerHTML += nameCut[i] + ' <span onclick="delZTypeEmployee(' + inputCut[i] + ');" style="cursor: pointer;"><img src="../img/admin/delete.gif" /></span><br />';
							}
							else
								$('#selectAccessories').append('<option selected="selected" value="' + inputCut[i] + '-' + nameCut[i] + '">' + inputCut[i] + ' - ' + nameCut[i] + '</option>');
						}
					
						$('#employee_autocomplete_input').setOptions({
							extraParams: {excludeIds : getZemployeeIds()}
						});
					}
				</script>
<?php 	
		echo '
				</div>
				<div class="clear">&nbsp;</div>';
        echo '
            	<hr class="clear">
            	<div  style="text-align: center">
                    <input type="submit" value="' . $this->l('   Save   ') . '" name="submitAdd' . $this->table . '" class="button" />
                </div>
                <div class="small"><sup>*</sup> '.$this->l('Required field').'</div>
            </div>';
        
    }

    /**
     *  display tab Staff
     *
     * @param <type> $obj
     */
    public function displayStaffTab($obj){
    	global $cookie;
        echo '
            <div class="tab-page" id="step2">
                <h4 class="tab">2. '.$this->l('Staff .').'</h4>';
        
	     if(!$obj->id){
//				echo $this->l('show number of staff in department');
	        }else{
	            echo ZDepartmentObject::_countRowStaffById($obj->id).$this->l(' staff in department "').htmlentities($this->getFieldValue($obj, 'name', (int)$cookie->id_lang)).'"';
	        }
        
        echo '
        		<hr class="clear">';
        $this->staffGrid->department_staff = $obj->id;      
        $this->staffGrid->display($this->token);        
        echo '  
        		<hr class="clear">     
                <div  style="text-align: center">
                    <input type="submit" value="' . $this->l('   Save   ') . '" name="submitAdd' . $this->table . '" class="button" />
                </div>
                <div class="small"><sup>*</sup> '.$this->l('Required field').'</div>
            </div>';
    }

	function display()
	{
		parent::display();
	}
	
	/**
     *  prepare JS for editor
     *
     * @global  $cookie
     */
    public function _prepareJs(){
        // TinyMCE
        global $cookie;
        $iso = Language::getIsoById((int)($cookie->id_lang));
        $isoTinyMCE = (file_exists(_PS_ROOT_DIR_.'/js/tiny_mce/langs/'.$iso.'.js') ? $iso : 'en');
        $ad = dirname($_SERVER["PHP_SELF"]);
        echo '
                <script type="text/javascript">
                var iso = \''.$isoTinyMCE.'\' ;
                var pathCSS = \''._THEME_CSS_DIR_.'\' ;
                var ad = \''.$ad.'\' ;
                </script>
                <script type="text/javascript" src="'.__PS_BASE_URI__.'js/tiny_mce/tiny_mce.js"></script>
                <script type="text/javascript" src="'.__PS_BASE_URI__.'js/tinymce.inc.js"></script>
                ';
    }
    /**
     * @see admintab->afterAdd($obj) 
     * run code after add neww
     * @param object add new $obj
     */
	protected function afterAdd($obj){
        $employee = ToolsCore::getValue('employeeBox');
        $obj->addEmployeeToStaff($obj, $employee);

    }
	/**
	 * @see admintab->afterUpdate($obj)
	 * run code after Update
	 * @param object $obj
	 */
    protected function afterUpdate($obj){
    	$employee = ToolsCore::getValue('employeeBox');
        $obj->addEmployeeToStaff($obj, $employee);
    }
    
}
	
